package pers.qianyu.month_202103.date_20210329;

import org.junit.Assert;
import org.junit.Test;

/**
 * 190. 颠倒二进制位
 * https://leetcode-cn.com/problems/reverse-bits/
 *
 * @author mizzle rain
 * @date 2021-03-29 10:34
 */
public class ReverseBits {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int r = 0;
        for (int i = 31; i >= 0; i--) {
            int t = (n >>> i) & 1;
            r += t << (31 - i);
        }
        return r;
    }

    private static final int M1 = 0x55555555; // 01010101010101010101010101010101
    private static final int M2 = 0x33333333; // 00110011001100110011001100110011
    private static final int M4 = 0x0f0f0f0f; // 00001111000011110000111100001111
    private static final int M8 = 0x00ff00ff; // 00000000111111110000000011111111

    // 分治
    public int reverseBits2(int n) {
        n = n >>> 1 & M1 | (n & M1) << 1;
        n = n >>> 2 & M2 | (n & M2) << 2;
        n = n >>> 4 & M4 | (n & M4) << 4;
        n = n >>> 8 & M8 | (n & M8) << 8;
        return n >>> 16 | n << 16;
    }

    @Test
    public void test1() {
        int r = new ReverseBits().reverseBits(0b00000010100101000001111010011100);
        Assert.assertEquals(964176192, r);
    }
}
